/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\QuotaManage\Report\QuotaMonitoringReport\components\CompanyTab.tsx
 * @Date: 2022-01-12 16:34:32
 * @LastEditTime: 2022-06-29 15:56:19
 */

import React from 'react'
import { UdTable, UdFilter, columnRenders, http, UdToolbar, UdModal } from '@/lib'
import UdSelect from '@/components/UdFormControls/UdSelect'
import quotaApis from '@/apis/AboutQuota'
import apis from '@/apis'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import dayjs from 'dayjs'
import { Button, Spin } from 'antd'
import { downBlobFile } from '@/utils/methods'
import { InnerTable } from './InnerTable'
import isBetween from 'dayjs/plugin/isBetween'
dayjs.extend(isBetween)
export default class CompanyTab extends React.Component<IProps, IState> {
  protected filterForm: WrappedFormUtils = {} as WrappedFormUtils
  private brandList: ReadonlyArray<any> = this.props.brandList
  private tableProps: any = { scroll: { x: true } }
  private conditions: any = [
    {
      label: '品牌公司',
      id: 'brandCode',
      initialValue: this.brandList[0].value,
      render: (
        <UdSelect
          showSearch
          allowClear={false}
          options={this.brandList}
          onChange={value => {
            this.changeBrandCode(value)
          }}
        />
      ),
    },
    {
      label: '统计年份',
      id: 'stageYear',
      initialValue: dayjs().year() + '',
      render: () => (
        <UdSelect options={this.state.yearList} allowClear={false} showSearch={true} optionFilterProp="children" />
      ),
    },
    {
      label: '配额品项',
      id: 'prodBarcodes',
      render: () => <UdSelect allowClear={false} showSearch options={this.state.prodBarCodeList} mode="multiple" />,
    },
  ]

  constructor(props) {
    super(props)
    this.state = {
      uploading: false,
      downloading: false,
      dataSource: [],
      searchValues: {},
      page: 1,
      size: 10,
      total: 0,
      loading: false,
      prodBarCodeList: [],
      yearList: [],
      tableCloPrefix: '',
    }
  }

  render() {
    const { tableCloPrefix, loading, uploading, downloading, dataSource } = this.state
    const columns: any = [
      ['序号', 'id', (text, record, index) => index + 1, { width: '50px' }],
      { title: '品牌公司', dataIndex: 'brandNameShort', minWidth: '60px' },
      { title: '物料分类编码', dataIndex: 'prodBarcode', minWidth: '80px' },
      { title: '物料分类名称', dataIndex: 'prodBarname', minWidth: '120px' },
      { title: '统计年份', dataIndex: 'stageYear', minWidth: '60px' },
      // { title: `${tableCloPrefix}计划内标准配额总量`, dataIndex: 'standardQuotaYearSum', minWidth: '140px' },
      {
        title: `${tableCloPrefix}标准配额总量`,
        key: 'standardQuotaYearSumTitle',
        dataIndex: 'standardQuotaYearSumTitle',
        align: 'center',
        children: [
          {
            title: '计划内',
            align: 'center',
            dataIndex: 'standardQuotaYearSum',
            key: 'standardQuotaYearSum',
            width: 85,
          },
          {
            title: '计划外',
            align: 'center',
            dataIndex: 'standardQuotaYearSumWay',
            key: 'standardQuotaYearSumWay',
            width: 85,
          },
        ],
      },
      // { title: `${tableCloPrefix}计划内实际配额总量`, dataIndex: 'actualQuotaSum', minWidth: '140px' },
      {
        title: `${tableCloPrefix}实际配额总量`,
        key: 'actualQuotaSumTitle',
        dataIndex: 'actualQuotaSumTitle',
        align: 'center',
        children: [
          {
            title: '计划内',
            align: 'center',
            dataIndex: 'actualQuotaSum',
            key: 'actualQuotaSum',
            width: 85,
          },
          {
            title: '计划外',
            align: 'center',
            dataIndex: 'actualQuotaSumWay',
            key: 'actualQuotaSumWay',
            width: 85,
          },
        ],
      },
      // { title: `${tableCloPrefix}计划内订单总量`, dataIndex: 'useQuotaSum', minWidth: '140px' },
      {
        title: `已执行${tableCloPrefix}订单总量`,
        key: 'useQuotaSumTitle',
        dataIndex: 'useQuotaSumTitle',
        align: 'center',
        children: [
          {
            title: '计划内',
            align: 'center',
            dataIndex: 'useQuotaSum',
            key: 'useQuotaSum',
            width: 85,
          },
          {
            title: '计划外',
            align: 'center',
            dataIndex: 'useQuotaSumWay',
            key: 'useQuotaSumWay',
            width: 85,
          },
        ],
      },
      {
        title: `执行中${tableCloPrefix}订单总量`,
        key: 'usingQuotaSumTitle',
        dataIndex: 'usingQuotaSumTitle',
        align: 'center',
        children: [
          {
            title: '计划内',
            align: 'center',
            dataIndex: 'usingQuotaSum',
            key: 'usingQuotaSum',
            width: 85,
          },
          {
            title: '计划外',
            align: 'center',
            dataIndex: 'usingQuotaSumWay',
            key: 'usingQuotaSumWay',
            width: 85,
          },
        ],
      },
      // { title: `${tableCloPrefix}计划内配额执行进度(%)`, dataIndex: 'executionProgress', minWidth: '140px' },
      {
        title: `${tableCloPrefix}配额执行进度(%)`,
        key: 'executionProgressTitle',
        dataIndex: 'executionProgressTitle',
        align: 'center',
        children: [
          {
            title: '计划内',
            align: 'center',
            dataIndex: 'executionProgress',
            key: 'executionProgress',
            width: 85,
          },
          {
            title: '计划外',
            align: 'center',
            dataIndex: 'executionProgressWay',
            key: 'executionProgressWay',
            width: 85,
          },
        ],
      },
      // { title: `${tableCloPrefix}计划内订单费用金额`, dataIndex: 'orderAmount', minWidth: '140px' },
      {
        title: `${tableCloPrefix}配额执行进度(%)`,
        key: 'orderAmountTitle',
        dataIndex: 'orderAmountTitle',
        align: 'center',
        children: [
          {
            title: '计划内',
            align: 'center',
            dataIndex: 'orderAmount',
            key: 'orderAmount',
            width: 85,
          },
          {
            title: '计划外',
            align: 'center',
            dataIndex: 'orderAmountWay',
            key: 'orderAmountWay',
            width: 85,
          },
        ],
      },
      // { title: `${tableCloPrefix}计划内订单打款金额`, dataIndex: 'paymentAmount', minWidth: '140px' },
      {
        title: `${tableCloPrefix}订单打款金额`,
        key: 'paymentAmountTitle',
        dataIndex: 'paymentAmountTitle',
        align: 'center',
        children: [
          {
            title: '计划内',
            align: 'center',
            dataIndex: 'paymentAmount',
            key: 'paymentAmount',
            width: 85,
          },
          {
            title: '计划外',
            align: 'center',
            dataIndex: 'paymentAmountWay',
            key: 'paymentAmountWay',
            width: 85,
          },
        ],
      },
      {
        title: '操作',
        dataIndex: 'operate',
        fixedWidth: '80px',
        fixed: 'right',
        render: columnRenders.operate([{ title: '阶段操作', action: (text, record) => this.handleDetails(record) }]),
      },
    ]
    return (
      <Spin spinning={uploading || downloading} tip={uploading ? '上传中，请稍后...' : '下载中，请稍后...'}>
        <UdFilter
          getForm={form => {
            this.filterForm = form
          }}
          items={this.conditions}
          onSearch={values => {
            this.handleSearch(values)
          }}
          loading={loading}
          resetAfter={this.resetFilterHandle}
        />
        <UdToolbar
          other={
            <Button type="primary" onClick={this.exportTableExcel}>
              导出
            </Button>
          }
        ></UdToolbar>
        <UdTable
          rowKey={(record, index) => index + ''}
          bordered={true}
          loading={loading}
          columns={columns}
          dataSource={dataSource}
          onChange={this.handleChangePage}
          {...this.tableProps}
          pagination={{
            current: this.state.page,
            pageSize: this.state.size,
            total: this.state.total,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '40'],
            showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
          }}
        ></UdTable>
      </Spin>
    )
  }

  componentDidMount() {
    this.getYearList()
    this.changeBrandCode(this.brandList[0].value, this.getTableData)
  }

  private exportTableExcel = () => {
    this.setState({ downloading: true })
    let params = this.filterForm.getFieldsValue()
    let { stageYear, brandCode } = params
    let brandName = this.brandList.find(item => {
      return item.value === brandCode
    })?.title
    http
      .post(quotaApis.downloadQuotaControlTemplate, { ...params, type: 1 }, { responseType: 'arraybuffer' })
      .then(res => {
        if (!res.data.code) {
          downBlobFile(res.data, `${stageYear}-${brandName}-配额监控报表`)
        }
      })
      .finally(() => {
        this.setState({ downloading: false })
      })
  }

  private getYearList = () => {
    http.get(apis.GetQuotaAssessYearList).then(res => {
      const yearList = res.data?.map(({ year: value, name: title }) => ({ value: value + '', title })) || []
      this.setState({ yearList })
    })
  }

  private changeBrandCode = (value: any, callBack?: Function) => {
    this.filterForm.setFieldsValue({ prodBarcode: undefined }, () => {
      this.setState({ prodBarCodeList: [] }, () => {
        Promise.allSettled([this.getProdBarList(value)]).then((res: any) => {
          this.setState({ prodBarCodeList: res[0]?.value || [] }, () => {
            let { prodBarCodeList = [] } = this.state
            this.filterForm.setFieldsValue({ prodBarcode: prodBarCodeList?.[0]?.value }, () => {
              callBack && callBack()
            })
          })
        })
      })
    })
  }

  private getProdBarList = (value: any) => {
    return http
      .get(quotaApis.getProdBarList, {
        params: { brandCode: value },
      })
      .then(res => {
        const { data = [] } = res
        const prodBarCodeList = data.map(item => ({ value: item.code, title: item.name }))
        return prodBarCodeList
      })
  }

  private handleDetails = record => {
    const { brandName, prodBarname } = record
    UdModal.open({
      centered: true,
      title: `${brandName}-${prodBarname}`,
      width: '65%',
      content: <InnerTable record={record} type={1} />,
      footer: null,
    })
  }

  private handleChangePage = pagination => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      this.getTableData()
    })
  }
  private handleSearch = (values: any) => {
    this.setState({ page: 1 }, () => {
      this.getTableData()
    })
  }

  private resetFilterHandle = (form: WrappedFormUtils) => {
    this.setState({ dataSource: [], page: 1, total: 0 }, () => {
      this.changeBrandCode(this.brandList[0].value, this.getTableData)
    })
  }

  private getTableData = async () => {
    this.setState({ loading: true })
    const params = { ...this.filterForm.getFieldsValue() }
    try {
      let list: any = await http.post(quotaApis.dealerQuotaControlPage, {
        page: this.state.page,
        size: this.state.size,
        conditions: {
          type: 1,
          brandCode: this.brandList[0].value,
          stageYear: dayjs().year() + '',
          ...params,
        },
      })
      const dataSource = list.data?.content

      this.setState({
        dataSource,
        page: list.data.number,
        size: list.data.size,
        total: list.data.totalElements,
        loading: false,
        tableCloPrefix: dayjs().isBetween(`${params.stageYear - 1}-11-01`, `${params.stageYear}-11-01`, 'date', '[)')
          ? '截至当前'
          : '年度',
      })
    } catch (error) {
      this.setState({
        loading: false,
      })
    }
  }
}

interface IProps {
  brandList: any[]
}
interface IState {
  dataSource: any[]
  searchValues: {}
  page: any
  size: any
  total: any
  loading: boolean
  prodBarCodeList: any[]
  yearList: []
  downloading: boolean
  uploading: boolean
  tableCloPrefix: string
}
